#include "main.h"
#include "music.hpp"
#include "FreeRTOS.h"
#include "task.h"

static bool key_up_clicked()
{
    static bool pressed = false;
    if (HAL_GPIO_ReadPin(key_up_GPIO_Port, key_up_Pin) == GPIO_PIN_SET) {  // 按下状态
        if (!pressed) {
            pressed = true;
            return true;
        }
    } else {
        pressed = false;
    }
    return false;
}

static bool key_down_clicked()
{
    static bool pressed = false;
    if (HAL_GPIO_ReadPin(key_down_GPIO_Port, key_down_Pin) == GPIO_PIN_RESET) {
        if (!pressed) {
            pressed = true;
            return true;
        }
    } else {
        pressed = false;
    }
    return false;
}

static bool key_left_clicked()
{
    static bool pressed = false;
    if (HAL_GPIO_ReadPin(key_left_GPIO_Port, key_left_Pin) == GPIO_PIN_RESET) {
        if (!pressed) {
            pressed = true;
            return true;
        }
    } else {
        pressed = false;
    }
    return false;
}

static bool key_right_clicked()
{
    static bool pressed = false;
    if (HAL_GPIO_ReadPin(key_right_GPIO_Port, key_right_Pin) == GPIO_PIN_RESET) {
        if (!pressed) {
            pressed = true;
            return true;
        }
    } else {
        pressed = false;
    }
    return false;
}

void key_scan(void *)
{
    for (;;) {
        if (key_up_clicked()) {
            music_ctl->keyUp();
        }

        if (key_down_clicked()) {
            music_ctl->keyDown();
        }

        if (key_left_clicked()) {
            music_ctl->keyLeft();
        }

        if (key_right_clicked()) {
            music_ctl->keyRight();
        }
        vTaskDelay(20);
    }
}